package cn.shenzhenlizuosystemapp.Common.UI.InputActivity;

import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.vise.log.ViseLog;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

import cn.shenzhenlizuosystemapp.Common.Adapter.CheckAdapter.Port.CheckDelect;
import cn.shenzhenlizuosystemapp.Common.Adapter.CheckAdapter.WindowContinuousScanAdapter;
import cn.shenzhenlizuosystemapp.Common.Base.Myapplication;
import cn.shenzhenlizuosystemapp.Common.Base.Tools;
import cn.shenzhenlizuosystemapp.Common.DataAnalysis.CheckDataAnalysis.ChildCheckTag;
import cn.shenzhenlizuosystemapp.Common.DataAnalysis.InputDataAnalysis.ChildTag;
import cn.shenzhenlizuosystemapp.Common.Port.CheckPort.BatchScanDataCallBack;
import cn.shenzhenlizuosystemapp.Common.Scan.ScanRead;
import cn.shenzhenlizuosystemapp.Common.View.MyProgressDialog;
import cn.shenzhenlizuosystemapp.Common.View.RvLinearManageDivider;
import cn.shenzhenlizuosystemapp.Common.View.SessionLinearLayout;
import cn.shenzhenlizuosystemapp.R;

public class LibraryBatchScanWindowTools implements BatchScanDataCallBack, CheckDelect {

    private Context context;
    private SessionLinearLayout windowView;
    private static WindowManager windowManager;
    private static LibraryBatchScanWindowTools BatchScanTools;
    private WindowContinuousScanAdapter windowContinuousScanAdapter;

    private int CurrentNumber = 0;
    private int ToGive = 0;

    private boolean IsContinuous = false;
    private boolean IsScan = false;

    private EditText Et_One;
    private EditText Et_Two;
    private EditText Et_Three;
    private EditText Et_Four;
    private EditText Et_Five;

    private TextView Tv_One;
    private TextView Tv_Two;
    private TextView Tv_Three;
    private TextView Tv_Four;
    private TextView Tv_Five;
    private TextView Tv_Scan;

    private TextView Tv_Continuous;
    private TextView Tv_SubMit;

    private TextView Tv_SelectOne;
    private TextView Tv_SelectTwo;
    private TextView Tv_SelectThree;
    private TextView Tv_SelectFour;
    private TextView Tv_SelectFive;
    private TextView Tv_BarCodeNumber;
    private TextView Tv_Sure;

    private TextView Tv_OneClean;
    private TextView Tv_TwoClean;
    private TextView Tv_ThreeClean;
    private TextView Tv_FourClean;
    private TextView Tv_FiveClean;

    private TextView Tv_Back;

    private LinearLayout Ll_One;
    private LinearLayout Ll_Two;
    private LinearLayout Ll_Three;
    private LinearLayout Ll_Four;
    private LinearLayout Ll_Five;

    private LinearLayout Ll_Continuous;
    private LinearLayout Ll_SingleScan;

    private RecyclerView Rv_Continuous;
    private AVLoadingIndicatorView AiV_ThreeShow;

    private List<String> ScanData = new ArrayList<>();
    private List<String> CheckPostData = new ArrayList<>();

    public static LibraryBatchScanWindowTools getBatchScanTools(Context context) {
        if (BatchScanTools == null) {
            synchronized (LibraryBatchScanWindowTools.class) {
                if (BatchScanTools == null) {
                    BatchScanTools = new LibraryBatchScanWindowTools(context);
                }
            }
        }
        return BatchScanTools;
    }

    public LibraryBatchScanWindowTools(Context context) {
        this.context = context;
    }

    public void OpenWindow(List<ChildTag> checkTagList, final ScanRead scanRead, MyProgressDialog progressDialog) {
        try {
            //获取WindowManager实例
            windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            //获取窗口布局参数实例
            WindowManager.LayoutParams params = new WindowManager.LayoutParams();
            //设置窗口布局参数属性
            params.flags = WindowManager.LayoutParams.FLAG_FULLSCREEN | WindowManager.LayoutParams.FLAG_FULLSCREEN;
            //设置窗口半透明
            params.format = PixelFormat.TRANSLUCENT;
            //设置窗口类型
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                params.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                params.type = WindowManager.LayoutParams.TYPE_PHONE;
            }
            //获取窗口布局实例
            windowView = (SessionLinearLayout) View.inflate(context, R.layout.fragment_batch_scanmodule, null);
            //获取窗口布局中的按钮实例
            Ll_One = (LinearLayout) windowView.findViewById(R.id.Ll_One);
            Ll_Two = (LinearLayout) windowView.findViewById(R.id.Ll_Two);
            Ll_Three = (LinearLayout) windowView.findViewById(R.id.Ll_Three);
            Ll_Four = (LinearLayout) windowView.findViewById(R.id.Ll_Four);
            Ll_Five = (LinearLayout) windowView.findViewById(R.id.Ll_Five);
            Tv_Scan = (TextView) windowView.findViewById(R.id.Tv_Scan);
            Tv_Continuous = (TextView) windowView.findViewById(R.id.Tv_Continuous);
            Rv_Continuous = (RecyclerView) windowView.findViewById(R.id.Rv_Continuous);
            Tv_SubMit = (TextView) windowView.findViewById(R.id.Tv_SubMit);
            Tv_BarCodeNumber = (TextView) windowView.findViewById(R.id.Tv_BarCodeNumber);
            Tv_Sure = (TextView) windowView.findViewById(R.id.Tv_Sure);
            Ll_Continuous = (LinearLayout) windowView.findViewById(R.id.Ll_Continuous);
            Ll_SingleScan = (LinearLayout) windowView.findViewById(R.id.Ll_SingleScan);
            Tv_Back = (TextView) windowView.findViewById(R.id.Tv_Back);

            AiV_ThreeShow = (AVLoadingIndicatorView) windowView.findViewById(R.id.AiV_ThreeShow);
            Tv_BarCodeNumber.setText("0");
            InitRecycler(Rv_Continuous);

            if (Tools.IsObjectNull(checkTagList) && checkTagList.size() > 0 && checkTagList.size() <= 5) {
                for (int CheckIndex = 0; CheckIndex < checkTagList.size(); CheckIndex++) {
                    ViseLog.i("CheckIndex" + CheckIndex);
                    if (CheckIndex == 0) {
                        Ll_One.setVisibility(View.VISIBLE);
                        Tv_One = Ll_One.findViewById(R.id.Tv_One);
                        Tv_One.setText(checkTagList.get(CheckIndex).getName() + ":");
                        Et_One = (EditText) Ll_One.findViewById(R.id.Et_One);
                        Et_One.setSaveEnabled(false);
                        Tv_SelectOne = (TextView) Ll_One.findViewById(R.id.Tv_SelectOne);
                        Tv_SelectOne.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                ToGive = 1;
                            }
                        });
                        Tv_OneClean = (TextView) windowView.findViewById(R.id.Tv_OneClean);
                        Tv_OneClean.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Et_One.setText("");
                            }
                        });
                    } else if (CheckIndex == 1) {
                        Ll_Two.setVisibility(View.VISIBLE);
                        Tv_Two = Ll_Two.findViewById(R.id.Tv_Two);
                        Tv_Two.setText(checkTagList.get(CheckIndex).getName());
                        Et_Two = Ll_Two.findViewById(R.id.Et_Two);

                        Tv_SelectTwo = (TextView) Ll_Two.findViewById(R.id.Tv_SelectTwo);
                        Tv_SelectTwo.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                ToGive = 2;
                            }
                        });
                        Tv_TwoClean = (TextView) windowView.findViewById(R.id.Tv_TwoClean);
                        Tv_TwoClean.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Et_Two.setText("");
                            }
                        });
                    } else if (CheckIndex == 2) {
                        
                        Ll_Three.setVisibility(View.VISIBLE);
                        Tv_Three = Ll_Three.findViewById(R.id.Tv_Three);
                        Tv_Three.setText(checkTagList.get(CheckIndex).getName());
                        Et_Three = Ll_Three.findViewById(R.id.Et_Three);

                        Tv_SelectThree = (TextView) Ll_Three.findViewById(R.id.Tv_SelectThree);
                        Tv_SelectThree.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                ToGive = 3;
                            }
                        });

                        Tv_ThreeClean = (TextView) windowView.findViewById(R.id.Tv_ThreeClean);
                        Tv_ThreeClean.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Et_Three.setText("");
                            }
                        });
                        
                    } else if (CheckIndex == 3) {
                        Ll_Four.setVisibility(View.VISIBLE);
                        Tv_Four = Ll_Four.findViewById(R.id.Tv_Four);
                        Tv_Four.setText(checkTagList.get(CheckIndex).getName());
                        Et_Four = Ll_Four.findViewById(R.id.Et_Four);

                        Tv_SelectFour = (TextView) Ll_Four.findViewById(R.id.Tv_SelectFour);
                        Tv_SelectFour.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                ToGive = 4;
                            }
                        });

                        Tv_FourClean = (TextView) windowView.findViewById(R.id.Tv_FourClean);
                        Tv_FourClean.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Et_Four.setText("");
                            }
                        });
                    } else if (CheckIndex == 4) {

                        Ll_Five.setVisibility(View.VISIBLE);
                        Tv_Five = Ll_Five.findViewById(R.id.Tv_Five);
                        Tv_Five.setText(checkTagList.get(CheckIndex).getName());
                        Et_Five = Ll_Five.findViewById(R.id.Et_Five);

                        Tv_SelectFive = (TextView) Ll_Five.findViewById(R.id.Tv_SelectFive);
                        Tv_SelectFive.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                ToGive = 5;
                            }
                        });
                        Tv_FiveClean = (TextView) windowView.findViewById(R.id.Tv_FiveClean);
                        Tv_FiveClean.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Et_Five.setText("");
                            }
                        });
                    }
                }
            }
            CurrentNumber = checkTagList.size();
            Tv_Scan.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    scanRead.Read(false);
                }
            });

            Tv_Sure.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Ll_Continuous.setVisibility(View.VISIBLE);
                    Ll_SingleScan.setVisibility(View.GONE);
                }
            });

            Tv_SubMit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    SubMitData(scanRead);
                }
            });

            Tv_Back.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Ll_Continuous.setVisibility(View.GONE);
                    Ll_SingleScan.setVisibility(View.VISIBLE);
                }
            });

            Tv_Continuous.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (!IsContinuous) {
                        IsContinuous = true;
                        scanRead.Read(true);
                        Tv_Continuous.setText("停止连续扫描");
                    } else {
                        IsContinuous = false;
                        scanRead.Stop();
                        Tv_Continuous.setText(R.string.ContinuousScan);
                    }
                }
            });
            windowView.setDispatchKeyEventListener(mDispatchKeyEventListener);
            windowManager.addView(windowView, params);
        } catch (Exception e) {
            ViseLog.i("WindowTools OpenWindow Exception = " + e);
        }
    }

    public void Cancle() {
        if (Tools.getTools().IsObjectNull(windowManager) && Tools.getTools().IsObjectNull(windowView)) {
            try {
                if (Tools.IsObjectNull(ScanData)) {
                    ScanData.clear();
                }
                Myapplication.CleanScan();
                windowManager.removeView(windowView);
            } catch (Exception e) {
                e.printStackTrace();
                ViseLog.i("WindowTools Cancle Exception = " + e);
            }
        }
    }

    public void KillWindows() {
        windowManager = null;
        context = null;
        BatchScanTools = null;
    }

    private SessionLinearLayout.DispatchKeyEventListener mDispatchKeyEventListener = new SessionLinearLayout.DispatchKeyEventListener() {

        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                if (windowView.getParent() != null) {
                    Cancle();
                }
                return true;
            }
            return false;
        }
    };

    @Override
    public void RefreshData(String Data) {
        switch (ToGive) {
            case 1: {
                if (Et_One != null) {
                    Et_One.setText(Data);
                }
                break;
            }
            case 2: {
                if (Et_Two != null) {
                    Et_Two.setText(Data);
                }
                break;
            }
            case 3: {
                if (Et_Three != null) {
                    Et_Three.setText(Data);
                }
                break;
            }
            case 4: {
                if (Et_Four != null) {
                    Et_Four.setText(Data);
                }
                break;
            }
            case 5: {
                if (Et_Five != null) {
                    Et_Five.setText(Data);
                }
                break;
            }
        }
    }

    @Override
    public void RefreshRvData(String data) {
        if (data.contains("\n")) {
            String[] datalist = data.split("\n");
            for (String string : datalist) {
                if (ScanData != null && !ScanData.contains(string)) {
                    ScanData.add(string);
                    String LastString = "";
                    for (int c = 0; c < ToGive; c++) {
                        if (c == 0) {
                            if (Et_One != null) {
                                LastString += Et_One.getText().toString() + "\n";
                            }
                        } else if (c == 1) {
                            if (Et_Two != null) {
                                LastString += Et_Two.getText().toString() + "\n";
                            }
                        } else if (c == 2) {
                            if (Et_Three != null) {
                                LastString += Et_Three.getText().toString() + "\n";
                            }
                        } else if (c == 3) {
                            if (Et_Four != null) {
                                LastString += Et_Four.getText().toString() + "\n";
                            }
                        } else if (c == 4) {
                            if (Et_Five != null) {
                                LastString += Et_Five.getText().toString() + "\n";
                            }
                        }
                    }
                    CheckPostData.add(string + "\n" + LastString);
                    Tv_BarCodeNumber.setText("" + ScanData.size());
                    windowContinuousScanAdapter.notifyDataSetChanged();
                    ViseLog.i("CheckPostData.add = " + string + "\n" + LastString);
                }
            }
        } else {
            if (ScanData != null && !ScanData.contains(data)) {
                ScanData.add(data);
                String LastString = "";
                for (int c = 0; c < ToGive; c++) {
                    if (c == 0) {
                        if (Et_One != null) {
                            LastString += Et_One.getText().toString() + "\n";
                        }
                    } else if (c == 1) {
                        if (Et_Two != null) {
                            LastString += Et_Two.getText().toString() + "\n";
                        }
                    } else if (c == 2) {
                        if (Et_Three != null) {
                            LastString += Et_Three.getText().toString() + "\n";
                        }
                    } else if (c == 3) {
                        if (Et_Four != null) {
                            LastString += Et_Four.getText().toString() + "\n";
                        }
                    } else if (c == 4) {
                        if (Et_Five != null) {
                            LastString += Et_Five.getText().toString() + "\n";
                        }
                    }
                }
                CheckPostData.add(data + "\n" + LastString);
                Tv_BarCodeNumber.setText("" + ScanData.size());
                windowContinuousScanAdapter.notifyDataSetChanged();
                ViseLog.i("CheckPostData.add = " + data + "\n" + LastString);
            }
        }
    }

    public void Back() {
        Cancle();
    }


    private void InitRecycler(RecyclerView recyclerView) {
        LinearLayoutManager ScanTaskL = new LinearLayoutManager(context);
        ScanTaskL.setOrientation(ScanTaskL.VERTICAL);
        recyclerView.addItemDecoration(new RvLinearManageDivider(context, LinearLayoutManager.VERTICAL));
        recyclerView.setLayoutManager(ScanTaskL);
        windowContinuousScanAdapter = new WindowContinuousScanAdapter(context, ScanData, this);
        recyclerView.setAdapter(windowContinuousScanAdapter);
    }


    private void SubMitData(ScanRead scanRead) {
        Rv_Continuous.setVisibility(View.GONE);
        AiV_ThreeShow.setVisibility(View.VISIBLE);
        for (int submit = 0; submit < CheckPostData.size(); submit++) {
            scanRead.validation(CheckPostData.get(submit), submit);
        }
    }

    public void SubmitResult(List<Integer> success, List<Integer> error) {
        if (error.size() > 0) {
            windowContinuousScanAdapter.SetError(true);
        }

        for (int i = success.size() - 1; i >= 0; i--) {
            ScanData.remove(ScanData.get(success.get(i)));
            CheckPostData.remove(CheckPostData.get(success.get(i)));
        }
        windowContinuousScanAdapter.notifyDataSetChanged();
        Tv_BarCodeNumber.setText("" + ScanData.size());
        Rv_Continuous.setVisibility(View.VISIBLE);
        AiV_ThreeShow.hide();
    }

    public int GetDataSum() {
        if (CheckPostData != null) {
            return CheckPostData.size();
        }
        return -1;
    }

    @Override
    public void Delect(int pos) {
        CheckPostData.remove(pos);
        ScanData.remove(pos);
        windowContinuousScanAdapter.notifyDataSetChanged();
        Tv_BarCodeNumber.setText("" + ScanData.size());
    }
}
